﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace XML
{
    public partial class Form1 : Form
    {
        ProductsDal productDal = new ProductsDal();

        RolesDal roleDal = new RolesDal();

        List<Model.roles> roleList = null;
        List<Model.products> productList = null;

        RoleRelationshipDal relationDal = new RoleRelationshipDal();
        public Form1()
        {
            InitializeComponent();
            roleList = roleDal.DataTableToList(roleDal.GetList("").Tables[0]);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            PersonalRoles person = new PersonalRoles { roleColl = new List<Role> { new Role { RoleName = "Role1", MinNumbers = "1", MaxNumbers = "3" }, new Role { RoleName = "Role2" } } };

            BusinessRoles business = new BusinessRoles { roleColl = new List<Role> { new Role { RoleName = "Role1", MinNumbers = "1", MaxNumbers = "2" }, new Role { RoleName = "Role2", MinNumbers = "1" }, new Role { RoleName = "Role3" } } };

            RoleSet roleSet = new RoleSet { Personal = person, Business = business };

            //  richTextBox1.Text = XmlHelper.XmlSerialize(roleSet, Encoding.UTF8);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            foreach (var item in listPersonalRoles.SelectedItems)
            {
                string[] vals = item.ToString().Split(new char[] { ':' });

                string role_id = vals[0];
                bool isExist = false;

                for (int i = 0; i < dataGridPersonal.Rows.Count; i++)
                {
                    if (dataGridPersonal.Rows[i].Cells["p_role_id"].Value.ToString() == role_id)
                    {
                        isExist = true;
                        break;
                    }
                }

                if (isExist) continue;
                DataGridViewRow row = new DataGridViewRow();
                int rowID = dataGridPersonal.Rows.Add(row);
                dataGridPersonal.Rows[rowID].Cells["p_role_id"].Value = vals[0];
                dataGridPersonal.Rows[rowID].Cells["p_role_name"].Value = vals[1];
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            DataSet productsDataSet = productDal.GetList("");

            productList = productDal.DataTableToList(productsDataSet.Tables[0]);

            foreach (Model.products product in productList)
            {
                listProduct.Items.Add(product.product_id + ":" + product.product_name);
            }

            var personalRoles = from role in roleList where role.role_type == RoleType.Personal select role;

            foreach (Model.roles role in personalRoles)
            {
                listPersonalRoles.Items.Add(role.role_id + ":" + role.role_name);
            }


            var bussinessRoles = from role in roleList where role.role_type == RoleType.Bussiness select role;

            foreach (Model.roles role in bussinessRoles)
            {
                listBusinessRoles.Items.Add(role.role_id + ":" + role.role_name);
            }

            textBox1.Text = DbHelperSQL.GetSingle("select config_val from config WHERE config_id =1").ToString();
        }

        private void listProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            String selectedItem = listProduct.SelectedItem.ToString();

            String productId = selectedItem.Split(new Char[] { ':' })[0];


            dataGridPersonal.Rows.Clear();
            dataGridBusiness.Rows.Clear();
            DataTable relationDt = DbHelperSQL.Query(string.Format("select [product_id],[roles].[role_id],[roles].[role_name],[roles].[role_type] ,[linked_role],[maxnumber],[minnumber],[cust_val_func] from role_relationship LEFT JOIN roles ON role_relationship.role_id = roles.role_id where product_id={0}", productId)).Tables[0];
            foreach (DataRow dr in relationDt.Rows)
            {
                DataGridViewRow row = new DataGridViewRow();
                int rowID;
                if (dr["role_type"].ToString() == RoleType.Personal.ToString())
                {
                    rowID = dataGridPersonal.Rows.Add(row);
                    dataGridPersonal.Rows[rowID].Cells["p_role_id"].Value = dr["role_id"];
                    dataGridPersonal.Rows[rowID].Cells["p_role_name"].Value = dr["role_name"];
                    dataGridPersonal.Rows[rowID].Cells["p_linked_role"].Value = dr["linked_role"];
                    dataGridPersonal.Rows[rowID].Cells["p_maxnumber"].Value = dr["maxnumber"];
                    dataGridPersonal.Rows[rowID].Cells["p_minnumber"].Value = dr["minnumber"];
                    dataGridPersonal.Rows[rowID].Cells["p_cust_val_func"].Value = dr["cust_val_func"];

                }
                else
                {
                    rowID = dataGridBusiness.Rows.Add(row);
                    dataGridBusiness.Rows[rowID].Cells["b_role_id"].Value = dr["role_id"];
                    dataGridBusiness.Rows[rowID].Cells["b_role_name"].Value = dr["role_name"];
                    dataGridBusiness.Rows[rowID].Cells["b_linked_role"].Value = dr["linked_role"];
                    dataGridBusiness.Rows[rowID].Cells["b_maxnumber"].Value = dr["maxnumber"];
                    dataGridBusiness.Rows[rowID].Cells["b_minnumber"].Value = dr["minnumber"];
                    dataGridBusiness.Rows[rowID].Cells["b_cust_val_func"].Value = dr["cust_val_func"];
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            for (int i = dataGridPersonal.Rows.Count - 1; i >= 0; i--)
            {
                object select = dataGridPersonal.Rows[i].Cells["p_CheckBoxCol"].Value ?? "False";
                if (select.ToString() == "True")
                {
                    dataGridPersonal.Rows.RemoveAt(i);
                }
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            foreach (var item in listBusinessRoles.SelectedItems)
            {
                string[] vals = item.ToString().Split(new char[] { ':' });

                string role_id = vals[0];
                bool isExist = false;

                for (int i = 0; i < dataGridBusiness.Rows.Count; i++)
                {
                    if (dataGridBusiness.Rows[i].Cells["b_role_id"].Value.ToString() == role_id)
                    {
                        isExist = true;
                        break;
                    }
                }

                if (isExist) continue;
                DataGridViewRow row = new DataGridViewRow();
                int rowID = dataGridBusiness.Rows.Add(row);
                dataGridBusiness.Rows[rowID].Cells["b_role_id"].Value = vals[0];
                dataGridBusiness.Rows[rowID].Cells["b_role_name"].Value = vals[1];
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            for (int i = dataGridBusiness.Rows.Count - 1; i >= 0; i--)
            {
                object select = dataGridBusiness.Rows[i].Cells["b_CheckBoxCol"].Value ?? "False";
                if (select.ToString() == "True")
                {
                    dataGridBusiness.Rows.RemoveAt(i);
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            foreach (var product in listProduct.SelectedItems)
            {
                string productId = product.ToString().Split(new char[] { ':' })[0];

                string delSql = String.Format("DELETE FROM role_relationship WHERE product_id = {0}", productId);

                DbHelperSQL.ExecuteSql(delSql);

                dataGridPersonal.CommitEdit(DataGridViewDataErrorContexts.Commit);
                dataGridBusiness.CommitEdit(DataGridViewDataErrorContexts.Commit);


                foreach (DataGridViewRow row in dataGridPersonal.Rows)
                {
                    Model.role_relationship model = new Model.role_relationship();
                    model.product_id = int.Parse(productId);
                    model.linked_role = row.Cells["p_linked_role"].Value == null ? "" : row.Cells["p_linked_role"].Value.ToString();
                    model.role_id = int.Parse(row.Cells["p_role_id"].Value.ToString());
                    model.maxnumber = row.Cells["p_maxnumber"].Value == null ? "" : row.Cells["p_maxnumber"].Value.ToString();
                    model.minnumber = row.Cells["p_minnumber"].Value == null ? "" : row.Cells["p_minnumber"].Value.ToString();
                    model.cust_val_func = row.Cells["p_cust_val_func"].Value == null ? "" : row.Cells["p_cust_val_func"].Value.ToString();

                    relationDal.Add(model);
                }

                foreach (DataGridViewRow row in dataGridBusiness.Rows)
                {
                    Model.role_relationship model = new Model.role_relationship();
                    model.product_id = int.Parse(productId);
                    model.linked_role = row.Cells["b_linked_role"].Value == null ? "" : row.Cells["b_linked_role"].Value.ToString();
                    model.role_id = int.Parse(row.Cells["b_role_id"].Value.ToString());
                    model.maxnumber = row.Cells["b_maxnumber"].Value == null ? "" : row.Cells["b_maxnumber"].Value.ToString();
                    model.minnumber = row.Cells["b_minnumber"].Value == null ? "" : row.Cells["b_minnumber"].Value.ToString();
                    model.cust_val_func = row.Cells["b_cust_val_func"].Value == null ? "" : row.Cells["b_cust_val_func"].Value.ToString();

                    relationDal.Add(model);
                }

            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "Please select the path";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string foldPath = dialog.SelectedPath;
                textBox1.Text = foldPath;
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string updateSql = String.Format("update config SET config_val = '{0}' WHERE config_id =1", textBox1.Text);
            DbHelperSQL.ExecuteSql(updateSql);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            DataTable dtRelationship = DbHelperSQL.Query("select [product_id],[roles].[role_id],[roles].[role_name],[roles].[role_type],[roles].[country_format_vid] ,[linked_role],[maxnumber],[minnumber],[cust_val_func] from role_relationship LEFT JOIN roles ON role_relationship.role_id = roles.role_id").Tables[0];

            foreach (Model.products product in productList)
            {
                List<Role> pList = new List<Role>();
                List<Role> bList = new List<Role>();

                DataRow[] dataRows = dtRelationship.Select("product_id=" + product.product_id);

                foreach (DataRow dr in dataRows)
                {
                    Role role = new Role();

                    if (!string.IsNullOrEmpty(dr["country_format_vid"].ToString()))
                        role.CtryFrmatVID = dr["country_format_vid"].ToString();
                    if (!string.IsNullOrEmpty(dr["linked_role"].ToString()))
                        role.LinkedRole = dr["linked_role"].ToString();
                    if (!string.IsNullOrEmpty(dr["cust_val_func"].ToString()))
                        role.CustValidation = dr["cust_val_func"].ToString();
                    if (!string.IsNullOrEmpty(dr["maxnumber"].ToString()))
                        role.MaxNumbers = dr["maxnumber"].ToString();
                    if (!string.IsNullOrEmpty(dr["minnumber"].ToString()))
                        role.MinNumbers = dr["minnumber"].ToString();
                    if (!string.IsNullOrEmpty(dr["role_name"].ToString()))
                        role.RoleName = dr["role_name"].ToString();

                    if (dr["role_type"].ToString() == RoleType.Personal.ToString())
                    {
                        pList.Add(role);
                    }
                    else
                    {
                        bList.Add(role);
                    }
                }


                PersonalRoles person = new PersonalRoles { roleColl = pList };
                BusinessRoles business = new BusinessRoles { roleColl = bList };

                RoleSet roleSet = new RoleSet { Personal = person, Business = business };

                XmlHelper.XmlSerializeToFile(roleSet, textBox1.Text + "\\" + product.product_id + "_" + product.product_name + ".txt", Encoding.UTF8);
            }

            MessageBox.Show("Done!");
        }

        private void button8_Click(object sender, EventArgs e)
        {
            if (listProduct.SelectedItems.Count < 1)
            {
                MessageBox.Show("Please select a product.");
                return;
            }
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = true;
            fileDialog.Title = "Please select the file";
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                string file = fileDialog.FileName;
                RoleSet roleset = XmlHelper.XmlDeserializeFromFile<RoleSet>(file, Encoding.UTF8);

                foreach (var product in listProduct.SelectedItems)
                {
                    string productId = product.ToString().Split(new char[] { ':' })[0];

                    string delSql = String.Format("DELETE FROM role_relationship WHERE product_id = {0}", productId);

                    DbHelperSQL.ExecuteSql(delSql);

                   
                    foreach (Role role in roleset.Personal.roleColl)
                    {
                        Model.role_relationship model = new Model.role_relationship();


                        var dbRoles = from dbrole in roleList where dbrole.role_type == RoleType.Personal && dbrole.role_name == role.RoleName select dbrole;

                        Model.roles dbRole = dbRoles.First();

                        model.product_id = int.Parse(productId);
                        model.linked_role = role.LinkedRole;
                        model.role_id = dbRole.role_id;
                        model.maxnumber = role.MaxNumbers;
                        model.minnumber = role.MinNumbers;
                        model.cust_val_func = role.CustValidation;

                        relationDal.Add(model);
                    }



                    foreach (Role role in roleset.Business.roleColl)
                    {
                        Model.role_relationship model = new Model.role_relationship();


                        var dbRoles = from dbrole in roleList where dbrole.role_type == RoleType.Bussiness && dbrole.role_name == role.RoleName select dbrole;

                        Model.roles dbRole = dbRoles.First();

                        model.product_id = int.Parse(productId);
                        model.linked_role = role.LinkedRole;
                        model.role_id = dbRole.role_id;
                        model.maxnumber = role.MaxNumbers;
                        model.minnumber = role.MinNumbers;
                        model.cust_val_func = role.CustValidation;

                        relationDal.Add(model);
                    }


                }
            }



        }
    }
}
